package com.xjm_cloud_admin.config.security.filter;


import com.alibaba.fastjson2.JSON;
import com.xjm_cloud_admin.enums.ResultCodeEnum;
import com.xjm_cloud_admin.annotation.service.PermitAllUrlService;
import com.xjm_cloud_admin.constant.Constants;
import com.xjm_cloud_admin.security.pojo.LoginUser;
import com.xjm_cloud_admin.security.service.TokenService;
import com.xjm_cloud_admin.util.R;
import com.xjm_cloud_admin.util.SecurityUtils;
import com.xjm_cloud_admin.util.ServletUtils;
import com.xjm_cloud_admin.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * token过滤器 验证token有效性
 *
 * @author 浪漫写尽歌谱
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    /**
     * 允许匿名访问的地址
     */
    @Autowired
    private PermitAllUrlService permitAllUrl;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        AntPathMatcher antPathMatcher = new AntPathMatcher();

        //获取全部匿名访问的url并判断当前方法是否为匿名访问
        List<String> urls = permitAllUrl.getUrls();
        boolean isAnonymityUrl = urls.stream().anyMatch(url -> antPathMatcher.match(url, request.getRequestURI()));

        //图片资源或者匿名url直接放行
        if (antPathMatcher.match(Constants.RESOURCE_PREFIX + "/**", request.getRequestURI()) || isAnonymityUrl) {
            chain.doFilter(request, response);
            return;
        }

        //登入请求直接放行
        if (StringUtils.contains(request.getRequestURI(), "/login")) {
            chain.doFilter(request, response);
            return;
        }

        LoginUser loginUser = tokenService.getLoginUser(request);

        // token失效直接返回
        if (StringUtils.isNull(loginUser)) {
            ServletUtils.renderString(response, JSON.toJSONString(R.error(ResultCodeEnum.LOGIN_INVALID.getCode(), ResultCodeEnum.LOGIN_INVALID.getMessage())));
            return;
        }

        // 没有安全上下文就去验证token有效性
        if (StringUtils.isNull(SecurityUtils.getAuthentication())) {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }

        chain.doFilter(request, response);
    }
}
